"""
重要财务数据导出为Excel或csv
"""
from AStock.ASSetting import settings
from AStock.ASData import financial_dict_id_to_chinese
import argparse
import pandas as pd


def _export_to_df(report_date):
    # 资产负债表
    # 008货币资金 011应收账款 017存货 187总资产增长率(%)
    # 044应付账款 045预收款项 063负债合计
    # 210资产负债率(%) 073负债和所有者（或股东权益）合计

    # 现金流量表
    # 107经营活动产生的现金流量净额 119投资活动产生的现金流量净额
    # 128筹资活动产生的现金流量净额 158现金及现金等价物净增加额

    # 利润表
    # 134净利润 184净利润增长率(%)
    # 074一、营业总收入 183营业收入增长率(%)
    # 075二：营业总成本 308营业成本 077销售费用 078管理费用 080财务费用
    # 086三、营业利润 092四、利润总额
    # 206扣除非经常性损益后的净利润

    # 580财报公告日期
    fields_to_get = ['008', '011', '017', '187', '044',
                     '045', '063', '210', '073', '107',
                     '119', '128', '158', '134', '184',
                     '074', '183', '075', '308', '077',
                     '078', '080', '086', '092', '206',
                     '580']
    try:
        coll = settings.database.financial
        filter_fields = {f: 1 for f in fields_to_get}
        filter_fields.update({'code': 1, '_id': 0})
        reports = coll.find(
            {'report_date': int(report_date)},
            filter_fields
        )
        coll = settings.database.stock_info_tushare
        stocks = coll.find(
            {},
            {'code': 1, 'name': 1, 'industry': 1, '_id': 0}
        )
    except Exception as e:
        print(e)
        return None

    stock_info_dict = {stock['code']: stock for stock in stocks}
    report_list = []
    for report in reports:
        code = report['code']
        del report['code']

        # 可能库中不存在查找的域，此时填入0值，让表头显示
        for f in fields_to_get:
            if f not in report:
                report[f] = 0.0

        new_report = {'代码': code}
        stock_info = stock_info_dict[code] if code in stock_info_dict else None
        new_report['名称'] = stock_info.get('name', '')
        new_report['行业'] = stock_info.get('industry', '')
        for k, v in sorted(report.items()):
            new_report[k + financial_dict_id_to_chinese.get(k, '')] = v
        report_list.append(new_report)

    df = pd.DataFrame(report_list)
    df = df.sort_values(by="代码", ascending=True)
    # print(df.head())
    return df


def _main_(args):
    file = args.file
    report_date = args.date
    df = _export_to_df(report_date)
    if df is None:
        print('export failed')
        return

    # columns = []
    if file.endswith('.xls') or file.endswith('.xlsx'):
        df.to_excel(file, encoding='utf-8', index=False)
    else:
        df.to_csv(file, encoding='utf-8', index=False, line_terminator='\n')

    print('Saved to {}'.format(file))


if __name__ == '__main__':
    argparser = argparse.ArgumentParser(description='export financial report')
    argparser.add_argument('-f', '--file', required=True,
                           help='full path file name to export to')
    argparser.add_argument('-d', '--date', required=True,
                           help='report date of financial to export, yyyymmdd format')
    args = argparser.parse_args()
    _main_(args)
